package io.netty.shenh.example.example1;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        // 判断msg是否是HttpRequest
        if (msg instanceof HttpRequest) {
            System.out.println("eventloop: " + ctx.channel().eventLoop());
            System.out.println("msg类型: " + msg.getClass());
            System.out.println("客户端地址: " + ctx.channel().remoteAddress());
            System.out.println("pipeline: " + ctx.channel().pipeline());

            HttpRequest httpRequest = (HttpRequest) msg;
            if ("/favicon.ico".equals(httpRequest.uri())) {
                return;
            }

            // 回复消息
            ByteBuf content = Unpooled.copiedBuffer("我是服务器", CharsetUtil.UTF_8);

            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);

            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
            response.headers().set(HttpHeaderNames.CONTENT_ENCODING, "utf-8");

            ctx.writeAndFlush(response);
        }
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }
}
